<script>
	import {
		mapMutations
	} from 'vuex';
	import WebSocket from '@/websocket/websocket.js'
	export default {
		onLaunch: function() {
			console.log('App Launch');
			let that = this;
			var statusBarHeight = uni.getSystemInfo({
				success: res => {
					// console.log(res)
					let statusBarHeight = res.statusBarHeight;
					that.$store.commit('setStatusBarHeight', statusBarHeight);
					that.$store.commit('setNavigationBarHeight', statusBarHeight + 44 + 1);
					that.$store.commit('setSafeAreaInsetsBottom', res.safeAreaInsets ? res.safeAreaInsets
						.bottom : 0);

					// #ifdef APP-PLUS
					that.$store.commit('setPlatform', 'APP');
					// #endif


					// #ifdef H5
					that.$store.commit('setPlatform', 'H5');
					// #endif


					// #ifdef MP-WEIXIN
					that.$store.commit('setPlatform', 'WEIXIN'); //该代码仅在微信小程序中生效
					const menuButtonInfo = wx.getMenuButtonBoundingClientRect().width;
					that.$store.commit('setWxMenuButtonWidth', menuButtonInfo);
					// #endif



				}
			});
			that.$store.commit('upTipsFlag', true)
		},
		onShow: function() {
			console.log('App Show');
			this.getUserInfo()
		},
		onHide: function() {
			console.log('App Hide');
			this.unsubscribe()
		},
		data() {
			return {
				// 重连间隔
				reconnectInterval: 5000,
				reconnectId: null,
				currentUserId: null,
			}
		},
		methods: {
			...mapMutations([
				'upUserInfo'
			]),
			getUserInfo() {
				let that = this
				that.$httpRequest.request({
					that: that,
					url: 'wechat/info',
					method: 'get',
					params: {},
					success: res => {
						if (res.code === that.$httpConfig.SUCCESS_CODE) {
							that.upUserInfo(res.data)
							that.currentUserId = res.data.id
							// 连接
							console.log("链接消息统计")
							// that.connect();
							// that.connectlisenter()
						} else {
							that.upUserInfo({})
						}
					}
				}, false)
			},
			connect() {
				WebSocket.init().then((client) => {
					console.log("消息初始化获取", client)
					client.subscribe( // 订阅
						`/topic/messageCount/${this.currentUserId}`,
						(frame) => {

							let params = JSON.parse(frame.body)
							this.$store.commit('upUnreadCount', params.unreadCount);
							console.log("消息统计", params)

						}, {
							ack: 'client1'
						} // 消息不会被确认接收，不确认每次连接都会推送
					)
				})
			},
			connectlisenter() {
				// 监听 WebSocket 连接关闭事件
				WebSocket.setCloseCallback((res) => {
					console.log('WebSocket消息统计关闭！', res);
					// 在此处添加关闭事件的逻辑处理
					// 重连
					this.reconnectId = setTimeout(() => {
						this.reconnect()
					}, this.reconnectInterval)
				});
			},
			//重新连接
			reconnect() {

				this.connect()
			},
			unsubscribe() {
				WebSocket.disconnect()
				// 停止重连事件
				if (this.reconnectId) {
					clearTimeout(this.reconnectId)
					this.reconnectId = null
				}
			},
		}
	};
</script>

<style lang="scss">
	/*每个页面公共css */
	@import '~@/style/common.scss'; // “~”是 stylus-loader中的定义
</style>